package com.yly.doctorapp.ui.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yly.doctorapp.R;
import com.yly.doctorapp.adapter.PrescriptionAdapter;
import com.yly.doctorapp.base.BaseFragment;
import com.yly.doctorapp.base.DoctorAppApplication;
import com.yly.doctorapp.bean.PrescriptionBean;
import com.yly.doctorapp.bean.PrescriptionFirstBean;
import com.yly.doctorapp.bean.ResponsDataBean;
import com.yly.doctorapp.constant.Configution;
import com.yly.doctorapp.ui.prescription.PrescriptionDetailActivity;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PrescriptionFragment extends BaseFragment {
    @BindView(R.id.tv_untreated)
    TextView tvUntreated;
    @BindView(R.id.tv_already_processed)
    TextView tvAlreadyProcessed;
    @BindView(R.id.lv_prescription)
    ListView lvPrescription;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<PrescriptionBean> mPrescriptionList = new ArrayList<>();
    private PrescriptionAdapter adapter;
    private ClassicsHeader mClassicsHeader = null;
    private int pageNum = 1;
    private String type = "0";
    private List<PrescriptionBean> mPrescriptionNoList = new ArrayList<>();
    private List<PrescriptionBean> mPrescriptionYesList = new ArrayList<>();

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_prescription;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        adapter = new PrescriptionAdapter(getActivity(), mPrescriptionList);
        lvPrescription.setAdapter(adapter);
        mClassicsHeader = (ClassicsHeader) refreshLayout.getRefreshHeader();
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis()));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm"));
        refreshLayout.getLayout().bringChildToFront(lvPrescription);
        refreshLayout.setEnableAutoLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                mPrescriptionList.clear();
                if (null != DoctorAppApplication.mUserBean) {
                    initPrescriptionItem(DoctorAppApplication.mUserBean.getDoctorid() + "", pageNum, "20", type);
                }
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNum++;
                if (null != DoctorAppApplication.mUserBean) {
                    initPrescriptionItem(DoctorAppApplication.mUserBean.getDoctorid() + "", pageNum, "20", type);
                }
            }
        });
        lvPrescription.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mPrescriptionList && mPrescriptionList.size() > 0) {
                    Intent mIntent = new Intent(getActivity(), PrescriptionDetailActivity.class);
                    mIntent.putExtra("ANAGRAPHID", mPrescriptionList.get(position).getAnagraphId() + "");
                    mIntent.putExtra("PRESCRIPTIONTYPE", mPrescriptionList.get(position).getStatus());
                    mIntent.putExtra("INSTRUCTIONSFORTAKING", mPrescriptionList.get(position).getInfo());
                    mIntent.putExtra("DOSAGE", mPrescriptionList.get(position).getDosage());
                    startActivity(mIntent);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != DoctorAppApplication.mUserBean) {
            mPrescriptionList.clear();
            initPrescriptionItem(DoctorAppApplication.mUserBean.getDoctorid() + "", pageNum, "20", type);
        }
        changeButtonColor(Integer.parseInt(type));
    }

    private void initPrescriptionItem(String doctorid, int pageNumber, String pageSize, final String status) {
        RequestParams params = new RequestParams(Configution.HOST + Configution.QUERYHOMEITEM);
        params.addBodyParameter("doctorId", doctorid);
        params.addBodyParameter("pageNumber", "" + pageNumber);
        params.addBodyParameter("pageSize", pageSize);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mPrescriptionNoList.clear();
                mPrescriptionYesList.clear();
                LogUtil.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResponsDataBean responsDataBean = JSON.parseObject(result, ResponsDataBean.class);
                    if (!StringUtils.isEmpty(responsDataBean.getData())) {
                        PrescriptionFirstBean prescriptionFirstBean = JSON.parseObject(responsDataBean.getData(), PrescriptionFirstBean.class);
                        if (!StringUtils.isEmpty(prescriptionFirstBean.getList())) {
                            List<PrescriptionBean> prescriptionBeanList = JSON.parseArray(prescriptionFirstBean.getList(), PrescriptionBean.class);
                            if (null != prescriptionBeanList && prescriptionBeanList.size() > 0) {
                                for (int i = 0; i < prescriptionBeanList.size(); i++) {
                                    if (prescriptionBeanList.get(i).getStatus().equals("0")) {
                                        mPrescriptionNoList.add(prescriptionBeanList.get(i));
                                    } else {
                                        mPrescriptionYesList.add(prescriptionBeanList.get(i));
                                    }
                                }
                                if (status.equals("0")) {
                                    mPrescriptionList.addAll(mPrescriptionNoList);
                                } else {
                                    mPrescriptionList.addAll(mPrescriptionYesList);
                                }
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
                if (null != refreshLayout) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadmore();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.show(getActivity(), "网络连接中断", 100);
                adapter.notifyDataSetChanged();
                if (null != refreshLayout) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadmore();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @OnClick({R.id.tv_untreated, R.id.tv_already_processed})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_untreated:
                pageNum = 1;
                type = "0";
                mPrescriptionList.clear();
                if (null != DoctorAppApplication.mUserBean) {
                    initPrescriptionItem(DoctorAppApplication.mUserBean.getDoctorid() + "", pageNum, "20", type);
                }
                changeButtonColor(0);
                break;
            case R.id.tv_already_processed:
                pageNum = 1;
                type = "1";
                mPrescriptionList.clear();
                if (null != DoctorAppApplication.mUserBean) {
                    initPrescriptionItem(DoctorAppApplication.mUserBean.getDoctorid() + "", pageNum, "20", type);
                }
                changeButtonColor(1);
                break;
        }
    }

    private void changeButtonColor(int index) {
        switch (index) {
            case 0:
                tvUntreated.setTextColor(0xffa0524b);
                tvUntreated.setBackgroundColor(0xffede1df);
                tvAlreadyProcessed.setTextColor(0xff666666);
                tvAlreadyProcessed.setBackgroundColor(0xfff5f3f3);
                break;
            case 1:
                tvUntreated.setTextColor(0xff666666);
                tvUntreated.setBackgroundColor(0xfff5f3f3);
                tvAlreadyProcessed.setTextColor(0xffa0524b);
                tvAlreadyProcessed.setBackgroundColor(0xffede1df);
                break;
        }
    }
}
